package com.rd.teacher.jichao.day14;

public class TestABC1 {

    public static void main(String[] args) {
        ABCPrint print = new ABCPrint(3);
        new Thread(new RunnableA(print)).start();
        new Thread(new RunnableB(print)).start();
        new Thread(new RunnableC(print)).start();
    }

}

class RunnableA implements Runnable{

    ABCPrint print;

    public RunnableA(ABCPrint print) {
        super();
        this.print = print;
    }

    @Override
    public void run() {
        print.printA();
    }
}


class RunnableB implements Runnable{

    ABCPrint print;

    public RunnableB(ABCPrint print) {
        super();
        this.print = print;
    }

    @Override
    public void run() {
        print.printB();
    }
}

class RunnableC implements Runnable{

    ABCPrint print;

    public RunnableC(ABCPrint print) {
        super();
        this.print = print;
    }

    @Override
    public void run() {
        print.printC();
    }
}


class ABCPrint {

    // 当前打印到谁的标志
    private int num;

    public ABCPrint(int num) {
        this.num = num;
    }

    public void printA() {
        for (int i = 0; i < 5; i++) {
            synchronized (this) {
                // 如果num==1 才打印A
                while (num != 1) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print("A");
                num = 2;
                this.notifyAll();
            }
        }
    }

    public void printB(){
        for (int i = 0; i < 5; i++) {
            synchronized (this) {
                // 如果num==2 才打印B
                while (num != 2) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print("B");
                num = 3;
                this.notifyAll();
            }
        }
    }

    public void printC(){
        for (int i = 0; i < 5; i++) {
            synchronized (this) {
                // 如果num==2 才打印B
                while (num != 3) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print("C");
                num = 1;
                this.notifyAll();
            }
        }
    }
}